import axios from "axios";
import Qs from "qs";

export const service = axios.create({
  baseURL: "http://127.0.0.1:8888",
  headers: {
    "Content-Type": "multipart/form-data",
  },
  transformRequest(data, headers) {
    const contentType = headers["Content-Type"];
    if (contentType === "application/x-www-form-urlencoded") {
      return Qs.stringify(data);
    }
    return data;
  },
});

// 请求拦截
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截
service.interceptors.response.use(
  (response) => {
    if (response.status === 200 && response.statusText === "OK") {
      return response.data;
    }
    return Promise.reject(new Error(response.statusText || "一些不可预期错误"));
  },
  (error) => {
    return Promise.reject(error);
  }
);
